<template>
	<el-card class="box-card">
		<template #header>
			<div class="card-header">
				<el-button type="primary" :icon="Plus" @click="showTrademarkDialog"
					>添加</el-button
				>
			</div>
		</template>
		<!-- 表格 -->
		<el-table :data="trademarkList" border style="margin-bottom: 20px">
			<el-table-column label="序号" type="index" align="center" width="80" />
			<el-table-column prop="tmName" label="品牌名称" align="center" />
			<el-table-column label="品牌LOGO" align="center">
				<template v-slot="{ row }">
					<img
						style="object-fit: cover; height: 70px"
						:src="row.logoUrl"
						alt=""
					/>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="400">
				<template v-slot="{ row }">
					<el-button
						type="warning"
						title="修改"
						size="small"
						:icon="Edit"
						@click="toEditTrademarkInfo(row)"
					/>
					<el-button
						type="danger"
						title="删除"
						size="small"
						:icon="Delete"
						@click="toRemoveTrademarkInfo(row)"
					/>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页器 -->
		<el-pagination
			style="text-align: center"
			v-model:current-page="currentPage"
			v-model:page-size="pageSize"
			:page-sizes="[3, 5, 10, 20]"
			:small="small"
			:disabled="disabled"
			background
			layout="prev, pager, next, jumper,->,sizes,total"
			:total="total"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		/>

		<el-dialog v-model="dialogFormVisible" title="添加品牌">
			<el-form :model="trademarkInfo" ref="trademarkFormRef" :rules="rules">
				<el-form-item label="品牌名称" label-width="100px" prop="tmName">
					<el-input v-model="trademarkInfo.tmName" autocomplete="off" />
				</el-form-item>
				<el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
					<el-upload
						class="avatar-uploader"
						:action="`${BASE_URL}/admin/product/fileUpload`"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload"
					>
						<img
							v-if="trademarkInfo.logoUrl"
							:src="trademarkInfo.logoUrl"
							class="avatar"
						/>
						<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
						<template #tip>
							<div class="el-upload__tip">
								只能上传jpg/png等图片格式,且大小不能超过2Mb
							</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button type="primary" @click="submitForm(trademarkFormRef)">
						确认
					</el-button>
				</span>
			</template>
		</el-dialog>
	</el-card>
</template>

<script lang="ts">
export default {
	name: 'tradeMark',
}
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ref, onMounted, reactive } from 'vue'
import {
	reqGetTrademarkListData,
	reqRemoveTrademarkInfo,
	reqSaveTrademarkInfo,
	reqUpdateTrademarkInfo,
} from '@/api/product/trademark'
import type {
	TrademarkListModel,
	TrademarkInfoModel,
} from '@/api/product/model/trademarkModel'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'

const currentPage = ref(1)
const pageSize = ref(3)
const total = ref(0)
const small = ref(false)
const disabled = ref(false)
const trademarkList = ref<TrademarkListModel>([])
const dialogFormVisible = ref(false)
const trademarkFormRef = ref<FormInstance>()
const imageUrl = ref('')
const BASE_URL = import.meta.env.VITE_API_URL
const initTrademarkInfo = () => ({
	tmName: '',
	logoUrl: '',
})
const trademarkInfo = reactive<TrademarkInfoModel>(initTrademarkInfo())
const rules = reactive<FormRules>({
	tmName: [
		{ required: true, message: '品牌名称不能为空', trigger: 'blur' },
		{ min: 2, max: 6, message: '长度在2~6个字符之间', trigger: 'blur' },
	],
	logoUrl: [
		{
			required: true,
			message: '至少上传一张图片',
			trigger: 'change',
		},
	],
})

onMounted(() => {
	getTrademarkListData()
})
// 获取品牌数据
const getTrademarkListData = async () => {
	const result = await reqGetTrademarkListData(
		currentPage.value,
		pageSize.value
	)
	trademarkList.value = result.records
	total.value = result.total
}
// 修改页面品牌显示数量
const handleSizeChange = (val: number) => {
	pageSize.value = val
	currentPage.value = 1
	getTrademarkListData()
}
// 实现分页效果
const handleCurrentChange = (val: number) => {
	currentPage.value = val
	getTrademarkListData()
}
// 图片上传校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
	const imgArr = ['image/jpeg', 'image/png']
	if (!imgArr.includes(rawFile.type)) {
		ElMessage.error('图片格式只能是jpeg,jpg,png,请重新选择...')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('图片大小不能超过2Mb,请重新选择...')
		return false
	}
	return true
}
// 图片上传成功预览
const handleAvatarSuccess: UploadProps['onSuccess'] = (
	response,
	uploadFile
) => {
	imageUrl.value = URL.createObjectURL(uploadFile.raw!)
	trademarkInfo.logoUrl = response.data
	trademarkFormRef.value?.clearValidate(['logoUrl'])
}
// 添加品牌
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			if (trademarkInfo.id) {
				await reqUpdateTrademarkInfo(trademarkInfo)
			} else {
				await reqSaveTrademarkInfo(trademarkInfo)
				currentPage.value = 1
			}
			ElMessage.success('操作成功！')
			getTrademarkListData()
			dialogFormVisible.value = false
		} else {
			console.log('error submit!', fields)
		}
	})
}
// 添加成功清空数据
const showTrademarkDialog = () => {
	trademarkFormRef.value?.clearValidate()
	Object.assign(trademarkInfo, initTrademarkInfo())
	delete trademarkInfo.id
	dialogFormVisible.value = true
}
// 删除品牌
const toRemoveTrademarkInfo = (row: TrademarkInfoModel) => {
	ElMessageBox.confirm(`确定要删除${row.tmName}吗？`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await reqRemoveTrademarkInfo(row.id as number)
			ElMessage({
				type: 'success',
				message: '删除成功！',
			})
			getTrademarkListData()
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
}
// 编辑品牌
const toEditTrademarkInfo = (row: TrademarkInfoModel) => {
	Object.assign(trademarkInfo, row)
	dialogFormVisible.value = true
	trademarkFormRef.value?.clearValidate()
}
</script>

<style scoped>
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
